package com.yunquan.ohana.ui.photos.preview

import android.content.Intent
import android.os.Bundle
import android.view.MotionEvent
import androidx.recyclerview.widget.RecyclerView
import androidx.viewpager2.widget.ViewPager2
import com.google.gson.Gson
import com.google.gson.reflect.TypeToken
import com.shuyu.gsyvideoplayer.GSYVideoManager
import com.shuyu.gsyvideoplayer.utils.GSYVideoType
import com.yunquan.ohana.BR
import com.yunquan.ohana.R
import com.yunquan.ohana.base.ui.BaseActivity
import com.yunquan.ohana.databinding.ActivityPreviewBinding
import com.yunquan.ohana.entity.PhotosEntity
import com.yunquan.ohana.ui.photos.preview.adapter.PreviewAdapter
import com.yunquan.ohana.utils.StringUtils

class PreviewActivity : BaseActivity<ActivityPreviewBinding, PreviewViewModel>() {

    private var mAdapter: PreviewAdapter? = null
    private val dataList = mutableListOf<PhotosEntity>()
    private val checkedList = mutableMapOf<Long, PhotosEntity>()


    override fun initContentView(savedInstanceState: Bundle?): Int {
        return R.layout.activity_preview
    }

    override fun initVariableId(): Int {
        return BR.previewViewModel
    }

    override fun initData(savedInstanceState: Bundle?) {
        super.initData(savedInstanceState)
        GSYVideoType.setRenderType(GSYVideoType.GLSURFACE)
        GSYVideoType.enableMediaCodec()
        GSYVideoType.enableMediaCodecTexture()

        val bundle = intent.extras
        var index = bundle?.getInt("index") ?: 0
        index = if (index > 0) --index else index
        val ids = bundle?.getString("ids")
        val dataJson = bundle?.getString("data")
        val jsonType = object : TypeToken<List<PhotosEntity>>(){}.type
        val group = Gson().fromJson<List<PhotosEntity>>(dataJson,jsonType)
        dataList.addAll(group)
        if (!StringUtils.isEmpty(ids)) {
            val idList = ids!!.split(",")
            for (e in idList) {
                val idLong = e.toLong()
                val position = dataList.indexOfFirst { it.id == idLong }
                checkedList[idLong] = dataList[position]
            }
        }

        mAdapter = PreviewAdapter(this, dataList)
        binding!!.vpContent.adapter = mAdapter
        binding!!.vpContent.offscreenPageLimit = 3
        binding!!.vpContent.setCurrentItem(index, false)
        checkChange(index)
    }

    override fun initViewObservable() {
        super.initViewObservable()
        binding!!.btnNext.setOnClickListener {
            val ids = checkedList.keys.joinToString(",")
            val bundle = Bundle()
            bundle.putString("ids", ids)
            val intent = Intent()
            intent.putExtras(bundle)
            setResult(RESULT_EXIT_CODE,intent)
            finish()
        }
        binding!!.btnBack.setOnClickListener {
            val ids = checkedList.keys.joinToString(",")
            val bundle = Bundle()
            bundle.putString("ids", ids)
            val intent = Intent()
            intent.putExtras(bundle)
            setResult(RESULT_CODE, intent)
            finish()
        }
        binding!!.checkbox.setOnClickListener {
            val index = binding!!.vpContent.currentItem % dataList.size
            val item = dataList[index]
            if(checkedList[item.id] == null){
                checkedList[item.id!!] = item
                binding!!.checkbox.setImageResource(R.mipmap.ic_check_true)
            }else{
                checkedList.remove(item.id)
                binding!!.checkbox.setImageResource(R.mipmap.ic_check_false)
            }
        }
        binding!!.vpContent.registerOnPageChangeCallback(object : ViewPager2.OnPageChangeCallback() {
            override fun onPageSelected(position: Int) {
                super.onPageSelected(position)
                val index = position % dataList.size
                checkChange(index)
                val item = dataList[index]
                if (item.type!!.contains("video")) {
                    val mChildView = binding!!.vpContent.getChildAt(0) as RecyclerView
                    val mHolder = mChildView.findViewHolderForAdapterPosition(position)
                    if (mHolder is PreviewAdapter.ViewHolder) {
                        if (mHolder.videoView.isInPlayingState) {
                            mHolder.videoView.post {
                                GSYVideoManager.instance().setDisplay(mHolder.videoView.currentSurface)
                            }
                        } else {
                            mHolder.videoView.post {
                                mHolder.videoView.startPlayLogic()
                            }
                        }
                        GSYVideoManager.onResume(false)
                    }
                } else {
                    GSYVideoManager.onPause()
                }
            }
        })
    }

    override fun dispatchTouchEvent(ev: MotionEvent?): Boolean {
        if (ev!!.action == MotionEvent.ACTION_DOWN) {
            binding!!.vpContent.requestDisallowInterceptTouchEvent(true)
        }
        return super.dispatchTouchEvent(ev)
    }

    override fun onResume() {
        super.onResume()
        GSYVideoManager.onResume(false)
    }

    override fun onPause() {
        super.onPause()
        GSYVideoManager.onPause()
    }

    override fun onDestroy() {
        GSYVideoManager.releaseAllVideos()
        super.onDestroy()
    }

    private fun checkChange(index : Int){
        val item = dataList[index]
        if (checkedList[item.id] != null) {
            binding!!.checkbox.setImageResource(R.mipmap.ic_check_true)
        } else {
            binding!!.checkbox.setImageResource(R.mipmap.ic_check_false)
        }
    }

    companion object {
        const val RESULT_CODE = 10002
        const val RESULT_EXIT_CODE = 10003
    }
}